// 路径导入@别名配置
require('module-alias/register')
const path = require('path')
const Koa = require('koa')
const cors = require('@koa/cors')
const KoaStatic = require('koa-static')
const KoaLogger = require('koa-logger')
const Moment = require('moment')
const { koaBody } = require('koa-body')
const router = require('./router')
const errorHandle = require('./middlewares/errorMiddlewares/errorHandle')
const { httploggerMiddleware } = require('./middlewares/logMiddlewares/httpLog')
const R = require('./models/Response')
const { ERROR_SYSTEM_CODE } = require('./constants/errorCode')

const app = new Koa()
const logger = KoaLogger((str) => {
  // 使用日志中间件
  console.log(Moment().format('YYYY-MM-DD HH:mm:ss') + str)
})

app.use(KoaStatic(path.resolve(__dirname, './public')))
app.use(cors())
app.use(
  koaBody({
    multipart: true,
    parsedMethods: ['POST', 'PUT', 'PATCH', 'DELETE']
  })
)
app.use(logger)
app.use(httploggerMiddleware())
app.use(errorHandle)
app.use(router.routes()).use(router.allowedMethods())

app.on('error', (err, ctx) => {
  console.log(err)
  ctx.body = R.error(ERROR_SYSTEM_CODE.SYSTEM_ERROR)
})

app.listen(3000, () => {
  console.log('server is running on http://127.0.0.1:3000')
})
